package com.kyd.auth.kit;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author zhuangqi
 * @date 2018/8/16
 */
@Slf4j
@Component
public class JwtTokenProvider {

    private String jwtSecret = "kyd@123";
    private int jwtExpirationIns = 604800;

    /**
     * token 生成
     * @param id
     * @return
     */
    public String generateToken(Long id) {
        return Jwts.builder()
                .setSubject(Long.toString(id))
                .setIssuedAt(new Date())
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

    /**
     * 获取超时时间
     * @return
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + jwtExpirationIns * 1000);
    }



    /**
     * 校验token
     * @param authToken
     * @return
     */
    public boolean validateToken(String authToken) {
        try {
            Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
            return true;
        } catch (SignatureException ex) {
            log.info("Invalid JWT signature");
        } catch (MalformedJwtException ex) {
            log.info("Invalid JWT token");
        } catch (ExpiredJwtException ex) {
            log.info("Expired JWT token");
        } catch (UnsupportedJwtException ex) {
            log.info("Unsupported JWT token");
        } catch (IllegalArgumentException ex) {
            log.info("JWT claims string is empty.");
        }
        return false;
    }


}
